package com.goke.media.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.goke.media.R;
import com.goke.media.ui.call.VoiceCallActivity;

public class LoginActivity extends AppCompatActivity {

    private LoginViewModel loginViewModel;
    private String server, username, password;
    private String version =
            "Author: chival366\n" +
            "E-mail: 794960056@qq.com\n" +
            "Source: github.com/chival366\n" +
            "Date:   2020/2/24 10:00"
            ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_login );

        loginViewModel = ViewModelProviders.of( this, new LoginViewModelFactory() )
                .get( LoginViewModel.class );

        final TextView versionEditText = findViewById( R.id.textViewVersion );
        final EditText serverEditText = findViewById( R.id.server );
        final EditText proxyEditText = findViewById( R.id.proxy );
        final EditText usernameEditText = findViewById( R.id.username );
        final EditText passwordEditText = findViewById( R.id.password );
        final Button loginButton = findViewById( R.id.login );
        final ProgressBar loadingProgressBar = findViewById( R.id.loading );

        loginViewModel.getLoginFormState().observe( this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {
                if (loginFormState == null) {
                    return;
                }
                loginButton.setEnabled( loginFormState.isDataValid() );
                if (loginFormState.getUsernameError() != null) {
                    usernameEditText.setError( getString( loginFormState.getUsernameError() ) );
                }
                if (loginFormState.getPasswordError() != null) {
                    passwordEditText.setError( getString( loginFormState.getPasswordError() ) );
                }
            }
        } );

        loginViewModel.getLoginResult().observe( this, new Observer<LoginResult>() {
            @Override
            public void onChanged(@Nullable LoginResult loginResult) {
                if (loginResult == null) {
                    return;
                }
                loadingProgressBar.setVisibility( View.GONE );
                if (loginResult.getError() != null) {
                    showLoginFailed( loginResult.getError() );
                }
                if (loginResult.getSuccess() != null) {
                    updateUiWithUser( loginResult.getSuccess() );
                }
                setResult( Activity.RESULT_OK );

                //Complete and destroy login activity once successful
                finish();
            }
        } );

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged( usernameEditText.getText().toString(),
                        passwordEditText.getText().toString() );
            }
        };
        usernameEditText.addTextChangedListener( afterTextChangedListener );
        passwordEditText.addTextChangedListener( afterTextChangedListener );
        passwordEditText.setOnEditorActionListener( new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    loginViewModel.login( usernameEditText.getText().toString(),
                            passwordEditText.getText().toString() );
                }
                return false;
            }
        } );

        loginButton.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*loadingProgressBar.setVisibility(View.VISIBLE);
                loginViewModel.login(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());*/

                setupCallActivity(
                        serverEditText.getText().toString(),
                        proxyEditText.getText().toString(),
                        usernameEditText.getText().toString(),
                        passwordEditText.getText().toString()
                );
            }
        } );

        versionEditText.setText(version);
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString( R.string.welcome ) + model.getDisplayName();
        // TODO : initiate successful logged in experience
        Toast.makeText( getApplicationContext(), welcome, Toast.LENGTH_LONG ).show();

        //setupCallActivity(user);
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText( getApplicationContext(), errorString, Toast.LENGTH_SHORT ).show();
    }

    private void setupCallActivity(String server, String proxy, String username, String password) {
        Intent intent = new Intent( this, VoiceCallActivity.class );
        intent.putExtra( "server", server );
        intent.putExtra( "proxy", proxy );
        intent.putExtra( "username", username );
        intent.putExtra( "password", password );

        startActivity( intent );
    }

}
